﻿using Loogn.OrmLite;
using Loogn.OrmLite.MySql;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.Extensions.Configuration;
using TaskCaller.Models;

namespace TaskCaller.Repositories
{
    public static class RepositoryServiceCollectionExtensions
    {
        private static IServiceCollection AddSqlServerRepository(IServiceCollection services)
        {
            services.AddSingleton<IDelayTaskRepository, SqlServer.DelayTaskRepository>();
            services.AddSingleton<IExecuteLogRepository, SqlServer.ExecuteLogRepository>();
            services.AddSingleton<ITimedTaskRepository, SqlServer.TimedTaskRepository>();
            services.AddSingleton<IManagerRespository, SqlServer.ManagerRepository>();
            return services;
        }

        private static IServiceCollection AddMySqlRepository(IServiceCollection services)
        {
            //注册mysql
            OrmLite.RegisterProvider(MySqlCommandDialectProvider.Instance);

            services.AddSingleton<IDelayTaskRepository, MySql.DelayTaskRepository>();
            services.AddSingleton<IExecuteLogRepository, MySql.ExecuteLogRepository>();
            services.AddSingleton<ITimedTaskRepository, MySql.TimedTaskRepository>();
            services.AddSingleton<IManagerRespository, MySql.ManagerRepository>();
            return services;
        }

        public static IServiceCollection AddTaskCallerRepository(this IServiceCollection services, IConfiguration configuration)
        {
            var config = configuration.GetSection("CallerServer").Get<CallerServerConfig>();

            if (config.DBType == "mysql")
            {
                return AddMySqlRepository(services);
            }
            else
            {
                return AddSqlServerRepository(services);
            }
        }
    }
}
